<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

require_once ('data/DataView.php');

class Config extends DataView
{

  /**
   *
   * @var Config
   */
  protected $parent;

  public function __construct(&$data = null, Config &$parent = null)
  {
    $this->parent = $parent;

    parent::__construct($data);
  }

  /**
   *
   * @return Config
   */
  public function parent()
  {
    return $this->parent ? $this->parent : $this;
  }

  /**
   *
   * @return Config
   */
  public function root()
  {
    return $this->parent() != $this ? $this->parent()->root() : $this;
  }

  protected function _get($name, $default = null)
  {
    extract($this->parsePath($name));

    if ($this->has($name)) {
      if ($name == '.') {
        return $sub === false ? $this->root() : $this->root()->get($sub, $default);
      }

      if ($name == '..') {
        return $sub === false ? $this->parent() : $this->parent()->get($sub, $default);
      }

      if ($sub === false) {
        return is_array($this->data) ? new Config($this->data[$name], $this) : $this->data[$name];
      }

      $node = new Config($this->data[$name], $this);
      return $node->get($sub, $default);
    }

    return is_array($default) ? new Config($default) : $this->resolveReferences($default);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/data/DataHolder#_has($name)
   */
  protected function _has($name)
  {
    extract($this->parsePath($name));

    if ($name == '.') {
      return true;
    }

    if ($name == '..') {
      return ! is_null($this->parent);
    }

    if (! isset($this->data[$name])) {
      return false;
    }

    if ($sub !== false) {
      $node = new Config($this->data[$name]);

      return $node->has($sub);
    }

    return true;
  }

  protected function _set($name, $value)
  {
    extract($this->parsePath($name));

    if ($sub === false) {
      if ($name == '.') {
        $this->root()->copyAll((array)$value);
      }
      elseif ($name == '..') {
        $this->parent()->copyAll((array)$value);
      }
      else {
        if (is_null($name) || $name == '') {
          $this->data[] = $this->resolveReferences($value);
        }
        else {
          if (! is_array($this->data)) {
            $this->data = (array) $this->data;
          }

          $this->data[$name] = $this->resolveReferences($value);
        }
      }
    }
    else {
      if ($name == '.') {
        $this->root()->set($sub, $value);
      }
      elseif ($name == '..') {
        $this->parent()->set($sub, $value);
      }
      else {
        if (! isset($this->data[$name])) {
          $this->data[$name] = array();
        }
        elseif (! is_array($this->data[$name])) {
          $this->data[$name] = (array) $this->data[$name];
        }

        $node = new Config($this->data[$name], $this);
        $node->set($sub, $value);
      }
    }

    return $this;
  }

  /**
   * Parse path info from $name.
   *
   * @param string $name the path
   * @return array
   */
  protected function parsePath($name)
  {
    $_name = $name;
    $path = explode(':', $name);
    $name = $this->resolveReferences($path[0]);

    $sub = ($p = strpos($_name, ':')) >= 1 ? (string) substr($_name, $p + 1) : false;

    return array(
      'path' => $path, 'name' => $name, 'sub' => $sub
    );
  }

  /**
   * Resolve references in the form {name}
   *
   * @param mixed $value
   * @return mixed
   */
  public function resolveReferences($value)
  {
    if (is_array($value)) {
      foreach ($value as &$val) {
        $val = $this->resolveReferences($val);
      }
    }
    elseif (is_string($value)) {
      while (false !== ($i = strpos($value, '{')) && false !== ($f = strpos($value, '}', $i))) {
        $find = substr($value, $i, $f - $i + 1);
        $name = substr($value, $i + 1, $f - $i - 1);

        $replace = strpos($name, ':') !== 0 ? $this->root()->get($name)->getAll() : $this->get(substr($name, 1))->getAll();

        if (is_array($replace)) {
          throw new Exception("Invalid reference in value <b>$value</b>: <b>$find</b>");
        }

        $value = str_replace($find, $replace, $value);
      }
    }

    return $value;
  }

  public function __toString()
  {
    return $this->getAll();
  }

}

?>